package com.mlst.twitterclientdemo;

import java.util.ArrayList;
import java.util.List;

import winterwell.jtwitter.Twitter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;

public class Main extends Activity {

    private ListView list;
    private ArrayList<String> twitMessages = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);

	list = (ListView) findViewById(R.id.twits);
	list.setAdapter(new CustomListAdapter());
	list.setCacheColorHint(0);
	
	new LoadTwits().execute();
    }

    class CustomListAdapter extends BaseAdapter {

	@Override
	public int getCount() {
	    return twitMessages.size();
	}

	@Override
	public Object getItem(int position) {
	    return twitMessages.get(position);
	}

	@Override
	public long getItemId(int position) {
	    return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
	    View view = convertView;
	    ListRowHandler row = null;
	    if (view == null) {
		view = getLayoutInflater().inflate(R.layout.itemlayout, null);
		row = new ListRowHandler(view);
		view.setTag(row);
	    } else {
		row = (ListRowHandler) view.getTag();
	    }

	    String twit = (String) getItem(position);
	    row.getTwit().setText(twit);

	    return view;
	}

    }

    class LoadTwits extends AsyncTask<String, String, String> {
	ProgressDialog pd;

	@Override
	protected void onPreExecute() {
	    pd = new ProgressDialog(Main.this);
	    pd.setMessage("Loading tweets");
	    pd.show();
	} 

	@Override
	protected String doInBackground(String... params) {
	    Twitter twitter = new Twitter("gtugdemo","password1111");
	    List<Twitter.Status> twits = twitter.search("#GTUG");
	    for (Twitter.Status status : twits) {
		twitMessages.add(status.getUser().getScreenName() + ": " + status.getText());
	    }

	    return null;
	}

	protected void onPostExecute(String result) {
	    if(pd != null && pd.isShowing()){
		pd.cancel();
	    }
	    
	    ((CustomListAdapter)list.getAdapter()).notifyDataSetInvalidated();
	};
    }
}